package com.user.test.view.fragments.searchResult

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.RecyclerView
import com.user.test.R
import com.user.test.databinding.ItemSearchResultBinding
import com.user.test.model.database.SearchResult
import okio.blackholeSink

class SearchResultAdapter(val link: MutableLiveData<String>) : RecyclerView.Adapter<SearchResultAdapter.SearchHolder>() {
    private val itemList = ArrayList<SearchResult>()
    private var holderClickable = true
    class SearchHolder(item: View, val link: MutableLiveData<String>): RecyclerView.ViewHolder(item){
        val binding = ItemSearchResultBinding.bind(item)

        fun bind(item: SearchResult, holderClickable : Boolean) {
            binding.rvTitleItem.text = item.title
            binding.rvThreadItem.text = item.threadPrecedence.toString()
            itemView.setOnClickListener {
                link.value = item.linkOnPage
            }
            itemView.isClickable = holderClickable

        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchHolder {
        return SearchHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_search_result, parent, false), link)
    }

    override fun onBindViewHolder(holder: SearchHolder, position: Int) {
        holder.bind(itemList[position], holderClickable)
    }

    override fun getItemCount(): Int {
        return itemList.size
    }

    @SuppressLint("NotifyDataSetChanged")
    fun addItem(item:SearchResult){
        itemList.add(item)
        notifyDataSetChanged()
    }

    @SuppressLint("NotifyDataSetChanged")
    fun addItemList(item: List<SearchResult>){
        itemList.addAll(item)
        notifyDataSetChanged()
    }

    @SuppressLint("NotifyDataSetChanged")
    fun setHoldersClickable(state : Boolean){
        holderClickable = state
        notifyDataSetChanged()
    }

}